/**
 * sms.send(手机号) 发送短信验证码
 * sms.verify(手机号,验证码) 校验验证码是否正确
 **/

const Core = require("@alicloud/pop-core")
const _ = require("lodash")

const client = new Core({
  accessKeyId: 'LTAI5tBDv6oE5Y6MJup5CpWr',
  accessKeySecret: 'S9FmaYhmxGcNPMbRZyXzLiFpH2aW9e',
  endpoint: 'https://dysmsapi.aliyuncs.com',
  apiVersion: '2017-05-25'
})

const params = {
  "SignName": "阿里云短信测试",
  "TemplateCode": "SMS_154950909",
}

const requestOption = {
  method: 'POST',
  formatParams: false,
}

exports.send = function(phone) {
  return new Promise((resolve, reject) => {
    const code = '' + _.random(9) + _.random(9) + _.random(9) + _.random(9)
    try {
      redisClient.set(phone, code, (err) => {
        if (err) {
          reject(err)
        }
      })
      client
        .request(
          "SendSms",
          {
            ...params,
            'PhoneNumbers': phone,
            'TemplateParam': `{\"code\":\"${code}\"}`
          },
          requestOption
        )
        .then(
          (result) => {
            if (
              result.Message &&
              result.Message == "OK" &&
              result.Code &&
              result.Code == "OK"
            ) {
              // 短信发送成功
              redisClient.expire(phone, 60 * 5 * 1000)
              resolve()
            } else {
              reject('短信发送失败！')
            }
          },
          (ex) => {
            reject(ex)
          }
        )
    } catch (error) {
      reject(error)
    }
  })
}

exports.verify = function(phone, code) {
  return new Promise((resolve, reject) => {
    redisClient.get(phone, (err, result) => {
      if (err) reject(err)
      else if (result) {
        if (result === code){
          resolve('验证通过！')
          redisClient.del(phone)
        } 
        resolve('验证码错误')
      }
      resolve('验证码过期！')
    })
  })
}
